import { useState, useEffect } from "react";

export function useCountdown() {
  const [countdown, setCountdown] = useState(0);
  const [isCounting, setIsCounting] = useState(false);
  const [onFinishCallback, setOnFinishCallback] = useState<
    ((isCounting: boolean) => void) | null
  >(null);

  // 初始化倒计时，恢复页面刷新前的状态
  useEffect(() => {
    const endTime = Number(localStorage.getItem("endTime"));
    if (endTime && endTime > Date.now()) {
      const remainingTime = Math.round((endTime - Date.now()) / 1000);
      setCountdown(remainingTime);
      setIsCounting(true);
    }
  }, []);

  // 倒计时逻辑
  useEffect(() => {
    if (isCounting && countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown((prevCount) => prevCount - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (countdown === 0 && isCounting) {
      clearCountdown();
      if (onFinishCallback) {
        onFinishCallback(isCounting); // 调用传入的回调函数
      }
    }
  }, [countdown, isCounting, onFinishCallback]);

  // 开始倒计时，并保存结束时间到 localStorage
  const startCountdown = (seconds: number = 30, onFinish?: () => void) => {
    const endTime = Date.now() + seconds * 1000;
    localStorage.setItem("endTime", endTime.toString());
    setIsCounting(true);
    setCountdown(seconds);
    setOnFinishCallback(() => onFinish || null); // 保存回调函数
  };

  // 清除倒计时
  const clearCountdown = () => {
    setIsCounting(false);
    localStorage.removeItem("endTime");
  };

  return {
    countdown,
    isCounting,
    startCountdown,
    clearCountdown,
  };
}
